﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using FirstFloor.ModernUI.Presentation;
using FirstFloor.ModernUI.Windows.Controls;
using IsikFx.Project.ClientApp.Helpers;
using IsikFx.Project.CommonTypes.CRUD;
using IsikFx.Project.Utils;
namespace IsikFx.Project.ClientApp.Pages
{
    /// <summary>
    /// Interaction logic for FirstLogin.xaml
    /// </summary>
    public partial class FirstLogin : UserControl
    {
        public FirstLogin()
        {
            InitializeComponent();
            ModernDialog dialog = new ModernDialog();
            dialog.Title = "IsikFx";
            dialog.Content = "IşıkFx uygulamasına hoşgeldiniz.";
            dialog.ShowDialog();
            Loaded += FirstLogin_Loaded;
        }

        void FirstLogin_Loaded(object sender, RoutedEventArgs e)
        {
            HideMenuLinks();
        }

        private void HideMenuLinks()
        {
            ModernWindow window = Window.GetWindow(this) as MainWindow;
            if (window.MenuLinkGroups != null && window.MenuLinkGroups.Count > 0)
            {
                LinkCollection linkCollection = window.MenuLinkGroups[0].Links;
                if (linkCollection != null)
                {
                    List<Link> links = linkCollection.ToList();
                    foreach (Link link in links)
                    {
                        link.DisplayName = "";
                    }
                }
            }
        }

        /// <summary>
        /// Inserts new user to the DB
        /// </summary>
        /// <param name="name">Name of the user</param>
        /// <param name="surname">Surname of the user</param>
        /// <param name="teamId">The user id of the team leader </param>
        /// <param name="salesOrRetail"> 0 for Sales 1 for Retantion </param>
        /// <param name="domainName"></param>
        private void InsertNewUser(string name, string surname, int teamId, int salesOrRetail, string domainName)
        {
            IsikFxWcfService.ServiceClient client = new IsikFxWcfService.ServiceClient();
            CrudResponseMessage responseMessage = client.InsertNewUser(name, surname, teamId, salesOrRetail, domainName);
            ModernDialog insertDialog = new ModernDialog();
            if (!responseMessage.HasError && responseMessage.Response.AffectedRows > 0)
            {
                insertDialog.Title = "Kayıt";
                insertDialog.Content = "Kaydınız başarılı bir şekilde oluşturuldu";
                insertDialog.ShowDialog();
            }
            else
            {
                insertDialog.Title = "Hata";
                insertDialog.Content = responseMessage.ErrorMessage;
                insertDialog.ShowDialog();
            }
        }

        private void btnSave_Click_1(object sender, RoutedEventArgs e)
        {
            if (ValidateForm())
            {
                try
                {
                    SavePhoto();
                    InsertNewUser(txtName.Text, txtSurName.Text, 1, 0, Environment.UserDomainName + "_" + Environment.UserName);
                }
                catch (Exception ex)
                {
                    ExceptionHelper.HandleException(ex, typeof(FirstLogin));
                    errorText.Text = "Fotoğrafınız kaydedilemedi, lütfen tekrar deneyiniz.";
                }
            }
            else
            {
                ModernDialog dialog = new ModernDialog();
                dialog.Title = "Hata";
                dialog.Content = "Lütfen alanları doldurunuz.";
                dialog.ShowDialog();
            }
        }

        private bool ValidateForm()
        {
            if (string.IsNullOrEmpty(txtName.Text) || string.IsNullOrEmpty(txtSurName.Text) || string.IsNullOrEmpty(txtImage.Text))
            {
                return false;
            }

            return true;
        }

        private void SavePhoto()
        {
            string fileName = txtName.Text + "_" + txtSurName.Text;
            string directoryExtension = System.Configuration.ConfigurationManager.AppSettings["PhotoFilePath"] as string;

            if (string.IsNullOrEmpty(directoryExtension))
            {
                throw new Exception("Teknik Hata");
            }

            string directory = System.IO.Path.Combine(System.IO.Path.GetTempPath(), directoryExtension);
            string fileExtension = System.IO.Path.GetExtension(txtImage.Text);
            string filePath = System.IO.Path.Combine(directory, fileName + fileExtension);

            SavePhotoToLocalPath(directory, filePath, fileName);
            SavePhotoToServer(txtImage.Text, string.Format("{0}{1}", fileName, fileExtension));
        }

        private void SavePhotoToLocalPath(string directory, string filePath, string fileName)
        {

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            File.Copy(txtImage.Text, filePath);
        }

        private bool SavePhotoToServer(string sourcefileName, string destinationFileName)
        {
            byte[] buffer;

            using (FileStream fs = new FileStream(sourcefileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
            }

            CrudResponseMessage responseMessage = Helper.SaveUserPhoto(destinationFileName, buffer);

            if (responseMessage != null && !responseMessage.HasError && responseMessage.Response != null && responseMessage.Response.AffectedRows > 0)
            {
                return true;
            }

            else
            {
                throw new Exception("Fotoğraf sunucuya yüklenemedi.");
            }
        }

        private void photoChooser_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog fileDialog = new Microsoft.Win32.OpenFileDialog();
            fileDialog.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";
            Nullable<bool> result = fileDialog.ShowDialog();

            if (result == true)
            {
                // photo.Source = new BitmapImage(new Uri(fileDialog.FileName));
                txtImage.Text = fileDialog.FileName;
            }
        }

    }
}
